package com.dries.security.browser.auth;

import cn.hutool.json.JSONUtil;
import com.dries.security.core.enums.LoginType;
import com.dries.security.core.properties.SecurityCoreProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description:
 * @Author ZSY
 * @createTime 2020/9/4 10:34
 */
@Slf4j
@Component("driesAuthSuccessHandler")
public class DriesAuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Resource
    private SecurityCoreProperties coreProperties;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth) throws IOException, ServletException {
        log.info("登录成功！");

        if (LoginType.JSON.equals(coreProperties.getBrowser().getLoginType())) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSONUtil.toJsonStr(auth));
        } else {
            super.onAuthenticationSuccess(request, response, auth);
        }
    }
}
